package experiment;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName GetBilibiliAid
 * @Date 2024/11/25 13:35 37
 * @Author Jack Chen
 * @Description serenity-cucumber-auto-project-jack
 * @Version 1.0
 */

public class GetBilibiliAid {

    public static void main(String[] args) throws IOException, InterruptedException {
        List<String> aid = new ArrayList<String>();
        String filePath = "./" + getCurrentDatetime() + "test.txt";
        By by = By.xpath("//*[@id=\"page-series-detail\"]/div/div/div/ul/li");
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
        driver.get("https://space.bilibili.com/1073905157/channel/seriesdetail?sid=2202629&ctype=0");
        do {
            List<WebElement> elements = driver.findElements(by);
            for (WebElement element : elements) {
                String txt = element.getText();
                System.out.println(txt);
                aid.add(element.getAttribute("data-aid"));
            }
        } while (hasNextPage(driver));

        String result = String.join("\n", aid);
        fileOutputStreamMethod(filePath, result);
        driver.quit();
    }

    private static boolean hasNextPage(WebDriver driver) throws InterruptedException {
        By by = By.xpath("//ul[@class='be-pager']/li[@class='be-pager-next']/a");
        if (elementExist(driver, by)) {
            driver.findElement(by).click();
            Thread.sleep(3000);
            return true;
        } else {
            System.out.println("页面遍历完成");
            return false;
        }
    }

    public static void fileOutputStreamMethod(String filepath, String content) throws IOException {
        try (FileOutputStream fileOutputStream = new FileOutputStream(filepath)) {
            byte[] bytes = content.getBytes();
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
        }
    }

    public static boolean elementExist(WebDriver driver, By by) {
        try {
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
            WebElement e = wait.until(ExpectedConditions.visibilityOfElementLocated(by));
            return e.isDisplayed();
        } catch (Exception e) {
            return false;
        }
    }

    public static String getCurrentDatetime() {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        return df.format(new Date());
    }
}
